/**
 * author:shinion
 * date:2019-09-20
 * 功能：
 *      1.通过canvans显示趋势图
 * 
 * 调用说明：
 *      1.首先调用init接口，进行初始化
 *      2.调用showTrendLine方法，绘制趋势图曲线和说明文字
 * 
 * 说明：
 *      此插件基于jqueyr，同时会使用到相关方法，引入前首先引入jquery和dataUtil
 * 
 */

Can_Trend = {};
Can_Trend.debug = true;//调试输出标记

Can_Trend.initFlg = false;          //初始化标记，true表示初始化完成，false表示未初始化
Can_Trend.ctx = null;               //画布对象,默认为null
Can_Trend.ctxLineColor = 'rgb(0,0,0)';
Can_Trend.ctxValColor = 'rgb(0,0,0)';

Can_Trend.div = {};//控件相关
Can_Trend.div.id = '';
Can_Trend.div.minWidth = 600;
Can_Trend.div.minHeight = 480;
Can_Trend.div.width = 0;
Can_Trend.div.height = 0;
Can_Trend.div.initWidth = 0;//第一次初始化时的宽度
Can_Trend.div.initHeight = 0;

Can_Trend.coor = {};                //坐标系相关
Can_Trend.coor.xText = "";          //x轴文字描述
Can_Trend.coor.yText = "";          //y轴文字描述
Can_Trend.coor.yLeft = 40;          //坐标系y轴距离左侧距离
Can_Trend.coor.yTop = 50;           //坐标系y轴距离上侧的距离
Can_Trend.coor.xRight = 90;         //坐标系x轴距离右侧距离
Can_Trend.coor.xBottom = 40;        //坐标系x轴距离下侧距离
Can_Trend.coor.minValue = 60;       //坐标系上y轴最小值和X轴距离
Can_Trend.coor.maxValue = 260;      //坐标系上y轴最大值和X轴距离
Can_Trend.coor.txtShiftValue = 12;  //文字偏移量

Can_Trend.data = {};                //数据相关
Can_Trend.data.valueMin = 100;       //数据最小值和x轴的距离，即和coor.xBottom的距离
Can_Trend.data.valueMax = 50;       //数据最大值和y轴顶部的距离，即和coor.yTop的距离
Can_Trend.data.xDisMin = 80;        //x轴上数据最小间距
Can_Trend.data.xDisMax = 110;        //x轴上数据最大间距

Can_Trend.data.trendListData = [];  //趋势数据


///////////////////////////////////////////////////////接口

/**
 * 初始化趋势图插件
 * 
 * @param id        canvas控件id
 * @param width     控件初始宽度
 * @param height    控件初始高度
 * @param xText     x轴文字描述
 * @param yText     y轴文字描述
 */
Can_Trend.init = function(id,width,height,xText,yText){
    this.div.id = id;
    this.div.width = width > this.div.minWidth ? width : this.div.minWidth;
    this.div.height = height > this.div.minHeight ? height : this.div.minHeight;
    this.div.initWidth = this.div.width;
    this.div.initHeight =  this.div.height;

    this.coor.xText = xText;
    this.coor.yText = yText;

    this.initDivs();
    this.initFlg = true;
}

/**
 * 显示趋势图
 * @param list 列表数据，例：[{text:'2019-09-20',value:34,valueHead:'报警描述'}]，value的值必须为数值,必须包含text和value,valueHead这三个属性
 * 
 */
Can_Trend.showTrendLine = function(list){
    if(this.initFlg == false){
        DataUtil.outError("控件未初始化，无法显示趋势图!");
    }else{
        if(!DataUtil.isDefined(list)){
            //显示趋势图
            this.showTrendListData(list);
        }else{
            //初始化坐标系
            this.initCoordinate();
            this.outDebug("要显示的数据列表为空!"); 
        }
        
    }
}

//接口，设置数据点个数 , 并根据个数初始化宽度
Can_Trend.setPointNums = function(nums){
    let objCan = document.getElementById(this.div.id);
    if(objCan != null && nums > 1){
        let nowWidth = objCan.width;
        let newWidth = this.data.xDisMin * (nums -1) + this.coor.yLeft + this.coor.xRight;
        if(newWidth > nowWidth ){//新宽度大于当前宽度
            this.div.width = newWidth;
            objCan.width = newWidth;
            // this.outDebug("重置画布宽度：width = " + newWidth);
        }else if(this.div.initWidth < newWidth){//新宽度大于初始宽度
            this.div.width = newWidth;
            objCan.width = newWidth;
        }else {//还原为初始化宽度
            this.div.width = this.div.initWidth;
            objCan.width = this.div.initWidth;
        }
    }
}
//////////////////////////////////////////////////////初始化

//初始化控件
Can_Trend.initDivs = function(){
    // this.outDebug("开始初始化控件,控件相关数据为：" , this.div);
    let objCan = document.getElementById(this.div.id);
    if(objCan != null ){
        objCan.width = this.div.width;
        objCan.height = this.div.height;
        // objCan.style.border = "1px solid orange";
    } 
    //初始化坐标系
    this.initCoordinate();
}

//初始化坐标系
Can_Trend.initCoordinate = function(){
    let msg = "";
    try {
        //清空画布
        let obj = document.getElementById(this.div.id);
        if(obj != null){
            obj.width = obj.width;
        }
        //开始绘制
        let ctx = this.getCtx();
        // this.outDebug("开始绘制......",ctx);
        ctx.fillStyle = this.ctxLineColor;
        ctx.strokeStyle = this.ctxLineColor;

        //绘制x轴
        let xstart_x = this.coor.yLeft;
        let xstart_y = this.div.height - this.coor.xBottom;
        // this.outDebug("start x,y : " + xstart_x + " , " + xstart_y);
        let xend_x = this.div.width - this.coor.xRight;
        let xend_y = this.div.height - this.coor.xBottom;
        // this.outDebug("end x,y : " + xend_x + " , " + xend_y);
        ctx.moveTo(xstart_x, xstart_y);
        ctx.lineTo(xend_x, xend_y);

        //绘制y轴
        let yend_x = this.coor.yLeft;
        let yend_y = this.coor.yTop;
        ctx.moveTo(xstart_x, xstart_y);
        ctx.lineTo(yend_x, yend_y);

        //绘制x轴信息
        ctx.fillText(this.coor.xText, xend_x - 2 * this.coor.txtShiftValue, xend_y + 2 * this.coor.txtShiftValue);

        //绘制y轴信息
        ctx.fillText(this.coor.yText, yend_x - 2 * this.coor.txtShiftValue, yend_y - this.coor.txtShiftValue);

        ctx.stroke();
    } catch (error) {
        msg += "初始化坐标系失败：" + error;
    }
    return msg;
}


//////////////////////////////////////////////////////显示趋势数据

//显示趋势列表数据
Can_Trend.showTrendListData = function(list){
    this.data.trendListData = list;
    let len = isNaN(list.length) ? 0 : list.length;//列表数量
    if (len > 0) {
        //解析数据
        this.formatTrendListData();

        //初始化
        this.initCoordinate();
        //显示数据
        this.drawTrendListData();
    } else {
        this.initCoordinate();
    }
    // this.outDebug("解析后的趋势列表数据：", this.data.trendListData);
}

//解析列表数据
Can_Trend.formatTrendListData = function(){
    let len = this.data.trendListData.length;
    let list = this.data.trendListData;
    //解析数据
    let xLineVal = this.div.height - this.coor.xBottom ;//x轴的基准值,用于绘制x轴下的文字
    let yLineVal = this.coor.yLeft;

    let xDis = this.div.width - this.coor.yLeft - this.coor.xRight;//x轴距离
    let yDis = this.div.height - this.coor.xBottom - this.coor.yTop - this.data.valueMin - this.data.valueMax;//y轴上的数据空间
    let yBasVal = this.div.height - this.coor.xBottom - this.data.valueMin;//y轴上基准值
    let xSignDis = 0;//x轴平均距离
    //只有一个数据
    if(len == 1){
        list[0].x = yLineVal;
        list[0].y = yBasVal - yDis/2;

        list[0].txt_x = list[0].x;
        list[0].txt_y = xLineVal + this.coor.txtShiftValue;
        //x轴上标记点的y值
        list[0].flg_y = xLineVal;

    }else{//多个数据
        //获取宽度，并判断宽度是否足够，如果不够，重设宽度
        xSignDis = Math.floor(xDis / (len -1));
        // this.outDebug("xDis = " + xDis + " , xSignDis = " + xSignDis);
        if(xSignDis < this.data.xDisMin){//平均单个数据位置太少，
            // let widthNew = this.data.xDisMin * (len -1) + this.coor.yLeft + this.coor.xRight;
            // let obj = document.getElementById(this.div.id);
            // if(obj != null ){
            //     this.div.width  =  widthNew;
            //     obj.width = widthNew;
            // }
            xSignDis = this.data.xDisMin;
        }
        if(xSignDis > this.data.xDisMax){
            xSignDis = this.data.xDisMax;
        }
        
        //获取最大最小值
        let tempList = [];
        $.each(list,function(n,item){
            tempList.push(item.value);
        });
        let max = Math.max.apply(Math,tempList);
        let min = Math.min.apply(Math,tempList);
        let valueCal = max - min;
        for(let i=0 ; i<len ; i++){
            //值坐标
            list[i].x = yLineVal + i * xSignDis;//x坐标

            if(list[i].value <= 0){//值为0
                list[i].y = this.div.height - this.coor.xBottom;
            }else{
                if(valueCal <= 0){// 差值为0
                    list[i].y = yBasVal;
                }else{//差值不为0
                    list[i].y = yBasVal - Math.floor(((list[i].value - min)*yDis/(valueCal)));
                }
            }

            //x轴上描述坐标
            list[i].txt_x = list[i].x;
            list[i].txt_y = xLineVal + this.coor.txtShiftValue;
            
            //x轴上标记点的y值
            list[i].flg_y = xLineVal;

        }
    }
}


//绘制趋势数据
Can_Trend.drawTrendListData = function(){
    let that = this;
    let list = this.data.trendListData;
    let ctx = that.getCtx();
    ctx.fillStyle = this.ctxValColor;
    ctx.strokeStyle = this.ctxValColor;
    if(ctx != null){
        $.each(list,function(n,item){
            //绘制折线
            if(n == 0){
                ctx.moveTo(item.x,item.y);
            }else{
                ctx.lineTo(item.x,item.y);
            }
            //绘制图上的点 
            ctx.arc(item.x, item.y, 2, 0, 2*Math.PI);//画点

            //绘制x轴上文字
            ctx.fillText(item.text, item.txt_x - 2*that.coor.txtShiftValue, item.txt_y);
            //绘制x轴上标记
            ctx.fillRect(item.txt_x,item.flg_y -4 ,2,4);

            //绘制y轴上的文字
            ctx.fillText(item.valueHead + " " + item.value,item.x + that.coor.txtShiftValue , item.y - that.coor.txtShiftValue);
        });
        ctx.stroke();
    }
}



//////////////////////////////////////////////////////公共方法
//输出调试信息
Can_Trend.outDebug = function(msg,data){
    if(this.debug ==  true){
        DataUtil.outDebug(msg,data)
    }
}

//获取画布对象
Can_Trend.getCtx = function(){
    let ctx = this.ctx;
    if(ctx == null){
        let canvas = document.getElementById(this.div.id);
        this.ctx = canvas.getContext("2d");
        ctx = this.ctx;
    }
    return ctx;
}

